package com.wjc.train.business.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wjc.train.business.entity.TrainCarriage;
import com.wjc.train.business.enums.SeatColEnum;
import com.wjc.train.business.repository.TrainCarriageRepository;
import com.wjc.train.business.req.TrainCarriageQueryReq;
import com.wjc.train.business.req.TrainCarriageSaveReq;
import com.wjc.train.business.resp.TrainCarriageQueryResp;
import com.wjc.train.business.service.ITrainCarriageService;
import com.wjc.train.common.enums.LogicEnum;
import com.wjc.train.common.exception.BusinessException;
import com.wjc.train.common.exception.BusinessExceptionCode;
import com.wjc.train.common.untils.CopyUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 车厢表 服务实现类
 * </p>
 *
 * @author Guessed
 * @since 2023-08-02
 */
@Service
public class TrainCarriageServiceImpl  implements ITrainCarriageService {

    @Resource
    private TrainCarriageRepository traincarriageRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(TrainCarriageSaveReq traincarriageSaveReq) {
        TrainCarriage dbTrainCarriage =
                traincarriageRepository.getOne(new QueryWrapper<TrainCarriage>()
                        .eq("train_code", traincarriageSaveReq.getTrainCode())
                        .eq("`index`",traincarriageSaveReq.getIndex())
                        .eq("is_deleted", LogicEnum.NOT_DELETED.getCode()));
        if(ObjectUtil.isNotEmpty(dbTrainCarriage)){
            throw new BusinessException("同车次车厢已存在");
        }
        TrainCarriage traincarriage = CopyUtil.copy(traincarriageSaveReq, TrainCarriage.class);
        //计算座位数
        int colSize = SeatColEnum.getColsByType(traincarriage.getSeatType()).size();
        traincarriage.setColumnCount(colSize);
        traincarriage.setSeatCount(colSize * traincarriage.getRowCount());
        traincarriageRepository.saveOrUpdate(traincarriage);
    }

    @Override
    public IPage<TrainCarriageQueryResp> queryList(IPage<TrainCarriageQueryResp> page, TrainCarriageQueryReq traincarriageQueryReq) {
        return traincarriageRepository.queryList(page,traincarriageQueryReq);
    }

    @Override
    public void delete(Long id) {
        traincarriageRepository.getBaseMapper().deleteById(id);
    }

    @Override
    public List<TrainCarriage> queryByTrainCode(String trainCode) {
        if(StringUtils.isBlank(trainCode)){
            throw new BusinessException(BusinessExceptionCode.PARAM_ERROR);
        }
        return traincarriageRepository.lambdaQuery()
                .eq(TrainCarriage::getTrainCode,trainCode).list();
    }
}
